package com.dafan.df_ronda_printer

import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result

import com.print.printlib.export.PrintApis

/** DfRondaPrinterPlugin */
class DfRondaPrinterPlugin: FlutterPlugin, MethodCallHandler {
  /// The MethodChannel that will the communication between Flutter and native Android
  ///
  /// This local reference serves to register the plugin with the Flutter Engine and unregister it
  /// when the Flutter Engine is detached from the Activity
  private lateinit var channel : MethodChannel

  // Print Apis
  private lateinit var printApis: PrintApis
  private var printApisObjID: Int = 0

  override fun onAttachedToEngine(flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
    channel = MethodChannel(flutterPluginBinding.binaryMessenger, "df_ronda_printer")
    channel.setMethodCallHandler(this)
    printApis = PrintApis(flutterPluginBinding.applicationContext, null)
  }

  override fun onMethodCall(call: MethodCall, result: Result) {
    if (call.method == "getPlatformVersion") {
      result.success("Android ${android.os.Build.VERSION.RELEASE}")
    } else if (call.method == "connectDevice") {
      val printAddr = call.argument<String>("printAddr")
      connectDevice(printAddr, result)
    } else if (call.method == "printAscii") {
      val printString = call.argument<String>("printString")
      printAscii(printString, result)
    } else if (call.method == "closeDevice") {
      closeDevice(result)
    } else {
      result.notImplemented()
    }
  }

  override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
    channel.setMethodCallHandler(null)
  }

  private fun connectDevice(printAddr: String?, result: Result) {
    printApisObjID = printApis.CON_ConnectDevices("RD-V2", printAddr)!!;
    //    val objID = printApis?.CON_ConnectDevices("V10_4668A2", "00:15:83:9B:63:D8");
    //    println("objID: ${printApisObjID}");
    result.success("$printApisObjID");
  }

  private fun closeDevice(result: Result) {
    val objCode = printApis.CON_CloseDevices(printApisObjID);
    result.success("$objCode")
  }

  private fun printAscii(printString: String?, result: Result) {
    if (printApisObjID!! > 0) {
      println("开始打印${printApisObjID}：$printString");
      var tempCode = printApis.CON_PageStart(printApisObjID);
      print("打印机状态 $tempCode");
      printApis.ASCII_PrintString(printApisObjID, printString, "gb2312");
      printApis.CON_PageEnd(printApisObjID);
      printApis.CON_PageSend(printApisObjID);
    }
  }
}
